package com.qdaily.supportlibrary.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.ExifInterface;
import android.net.Uri;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by song on 15/5/26.
 */
public class BitmapUtil {
    public static String saveBmp(Bitmap bmp, String path) {
        try {
            File file = new File(path);
            if (file.exists())
                file.delete();
            file.createNewFile();
            OutputStream stream = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.close();
            return path;
        } catch (Exception e) {}
        return null;
    }

    public static boolean saveBmp(Bitmap bmp, File file) {
        try {
            if (file.exists())
                file.delete();
            file.createNewFile();
            OutputStream stream = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.close();
            return true;
        } catch (Exception e) {}
        return false;
    }

    public static Bitmap getSquareIcon(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();

        Bitmap temp = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(temp);

        int dh = (height - width) / 2;

        Rect src = new Rect(0, dh, width, height-dh);
        Rect dst = new Rect(0, 0, width, width);

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        canvas.drawRect(dst, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bmp, src, dst, paint);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        temp.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        temp = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return temp;
    }

    public static Bitmap getRoundIcon(Bitmap bmp, int radius) {
        return getIcon(bmp, true, radius);
    }

    private static Bitmap getIcon(Bitmap bmp, boolean round, int size) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();

        Bitmap temp = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(temp);

        int dh = (height - width) / 2;

        Rect src = new Rect(0, dh, width, height-dh);
        Rect dst = new Rect(0, 0, width, width);

        Paint paint = new Paint();
        paint.setAntiAlias(true);

        RectF rectF = new RectF(dst);
        if (round)
//			canvas.drawRoundRect(rectF, width/2, width/2, paint);
            canvas.drawCircle(width/2, width/2, size, paint);
        else
            canvas.drawRect(rectF, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bmp, src, dst, paint);

        return temp;

    }

    public static Bitmap getBitmap(Context context, Uri uri) {
        InputStream in = null;
        try {
            Log.v("test", "uri.getPath() : " + uri.getPath());
            final int IMAGE_MAX_SIZE = 1024;
            in = context.getContentResolver().openInputStream(uri);

            //Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            BitmapFactory.decodeStream(in, null, o);
            in.close();

            int scale = 1;
            if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
            }

            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            in = context.getContentResolver().openInputStream(uri);
            Bitmap b = BitmapFactory.decodeStream(in, null, o2);
            in.close();

            return b;
        } catch (FileNotFoundException e) {
            Log.e("Cropper", "file " + uri.toString() + " not found");
        } catch (IOException e) {
            Log.e("Cropper", "file " + uri.getPath() + " not io");
        }
        return null;
    }


    public static Bitmap inverse(Bitmap bmp) {

        int bmpH = bmp.getHeight();
        int bmpW = bmp.getWidth();

        Bitmap newBmp = Bitmap
                .createBitmap(bmpW, bmpH, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(newBmp);
        Paint paint = new Paint();
        Matrix matrix = new Matrix();
        matrix.postScale(-1, 1, bmpW / 2, bmpH / 2);// 前两个是xy变换，后两个是对称轴中心点
        // matrix.postTranslate(x, y);
        canvas.drawBitmap(bmp, matrix, paint);

        return newBmp;
    }


    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
}